package com.dahaonetwork.smartfactory.websocket.base;

import java.io.IOException;
import java.util.Iterator;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dahaonetwork.smartfactory.websocket.model.Message;

public class PushMessageThread extends Thread{
	
	protected final Logger log = LoggerFactory.getLogger(this.getClass()); 
	
	/** 接受消息的socket集合 */
	private Set<WebSocket> sockets;
	
	/** 消息体 */
	private Message msg;
	/**
	 * default constructor
	 * @param sockets 接受消息的socket集合
	 * @param msg 消息体
	 */
	public PushMessageThread(Set<WebSocket> sockets, Message msg){
		this.sockets = sockets;
		this.msg = msg;
	}
	
	public void run() {
		Iterator<?> it = sockets.iterator();
		while(it.hasNext()){
			WebSocket socket = (WebSocket) it.next();
			//有可能在我获取到此socket之后，会由于前台的关闭，socket被移除，并关闭 TODO ↑
			try {
				socket.sendMessage(msg);
			} catch (IOException e) {
				log.error(e.getMessage(), e);
				log.warn("发送消息失败。", e);
			}
		}
	}

}
